<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="1 Spring Cloud Gateway 能做什么？  路由寻址（主要功能） 负载均衡 限流 鉴权">
<meta property="og:type" content="article">
<meta property="og:title" content="Gateway">
<meta property="og:url" content="http://littlefxc.github.io/2022/04/20/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Gateway/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="1 Spring Cloud Gateway 能做什么？  路由寻址（主要功能） 负载均衡 限流 鉴权">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/45680ad1cd1751edfb2ccbbe1c2eb829.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/f3feeb8bd2d96787d529875fddb5be63.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/f157b5764fb4d16c784ed4bc13f3e398.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/b895129eee8c7e9884625ff8ec753f9a.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/img_convert/5caf80b8df7d33ffdd1e9c940737c89d.png">
<meta property="article:published_time" content="2022-04-19T23:31:01.000Z">
<meta property="article:modified_time" content="2022-05-10T01:35:05.380Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="网关">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/img_convert/45680ad1cd1751edfb2ccbbe1c2eb829.png">


<link rel="canonical" href="http://littlefxc.github.io/2022/04/20/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Gateway/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Gateway | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-Spring-Cloud-Gateway-%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-text">1 Spring Cloud Gateway 能做什么？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-Gateway-VS-Zuul"><span class="nav-text">2 Gateway VS Zuul</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-Gateway-%E4%BD%93%E7%B3%BB%E6%9E%B6%E6%9E%84%E8%A7%A3%E6%9E%90"><span class="nav-text">3 Gateway 体系架构解析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-Gateway-%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D"><span class="nav-text">3.1 Gateway 自动装配</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E8%B7%AF%E7%94%B1%E5%8A%9F%E8%83%BD%E8%AF%A6%E8%A7%A3"><span class="nav-text">4 路由功能详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-%E8%B7%AF%E7%94%B1%E7%9A%84%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B"><span class="nav-text">4.1 路由的工作流程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E6%96%AD%E8%A8%80%E5%8A%9F%E8%83%BD%E8%AF%A6%E8%A7%A3"><span class="nav-text">5 断言功能详解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-Predicate-%E6%9C%BA%E5%88%B6"><span class="nav-text">5.1 Predicate 机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-%E6%96%AD%E8%A8%80%E7%9A%84%E4%BD%9C%E7%94%A8%E9%98%B6%E6%AE%B5"><span class="nav-text">5.2 断言的作用阶段</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-%E5%B8%B8%E7%94%A8%E6%96%AD%E8%A8%80%E4%BB%8B%E7%BB%8D"><span class="nav-text">5.3 常用断言介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-1-Path-%E6%96%AD%E8%A8%80"><span class="nav-text">5.3.1 Path 断言</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-2-Method-%E6%96%AD%E8%A8%80"><span class="nav-text">5.3.2 Method 断言</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-3-RequestParam%E5%8C%B9%E9%85%8D"><span class="nav-text">5.3.3 RequestParam匹配</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-4-Header-%E6%96%AD%E8%A8%80"><span class="nav-text">5.3.4 Header 断言</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-5-Cookie-%E6%96%AD%E8%A8%80"><span class="nav-text">5.3.5 Cookie 断言</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-6-%E6%97%B6%E9%97%B4%E7%89%87%E5%8C%B9%E9%85%8D"><span class="nav-text">5.3.6 时间片匹配</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-3-7-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%96%AD%E8%A8%80"><span class="nav-text">5.3.7 自定义断言</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E8%BF%87%E6%BB%A4%E5%99%A8%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="nav-text">6 过滤器的原理和生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1-%E8%BF%87%E6%BB%A4%E5%99%A8%E7%9A%84%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="nav-text">6.1 过滤器的设计模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2-%E8%BF%87%E6%BB%A4%E5%99%A8%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="nav-text">6.2 过滤器的实现方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-3-%E8%BF%87%E6%BB%A4%E5%99%A8%E7%9A%84%E6%89%A7%E8%A1%8C%E9%98%B6%E6%AE%B5"><span class="nav-text">6.3 过滤器的执行阶段</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-3-1-Pre-%E7%B1%BB%E5%9E%8B"><span class="nav-text">6.3.1 Pre 类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-3-2-Post-%E7%B1%BB%E5%9E%8B"><span class="nav-text">6.3.2 Post 类型</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-4-%E8%BF%87%E6%BB%A4%E5%99%A8%E4%BC%98%E5%85%88%E7%BA%A7"><span class="nav-text">6.4 过滤器优先级</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2022/04/20/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/Gateway/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Gateway
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-04-20 07:31:01" itemprop="dateCreated datePublished" datetime="2022-04-20T07:31:01+08:00">2022-04-20</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:35:05" itemprop="dateModified" datetime="2022-05-10T09:35:05+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%88%86%E5%B8%83%E5%BC%8F%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">分布式系统</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="1-Spring-Cloud-Gateway-能做什么？"><a href="#1-Spring-Cloud-Gateway-能做什么？" class="headerlink" title="1 Spring Cloud Gateway 能做什么？"></a>1 Spring Cloud Gateway 能做什么？</h2><p><img src="https://img-blog.csdnimg.cn/img_convert/45680ad1cd1751edfb2ccbbe1c2eb829.png" alt="image-20220420203439069"></p>
<ol>
<li>路由寻址（主要功能）</li>
<li>负载均衡</li>
<li>限流</li>
<li>鉴权</li>
</ol>
<span id="more"></span>

<h2 id="2-Gateway-VS-Zuul"><a href="#2-Gateway-VS-Zuul" class="headerlink" title="2 Gateway VS Zuul"></a>2 Gateway VS Zuul</h2><table>
<thead>
<tr>
<th></th>
<th>Gateway</th>
<th>Zuul 1.x</th>
<th>Zuul 2.x</th>
</tr>
</thead>
<tbody><tr>
<td>靠谱性</td>
<td>官方支持</td>
<td>曾经靠谱过</td>
<td>专业放鸽子</td>
</tr>
<tr>
<td>性能</td>
<td>Netty</td>
<td>同步阻塞、性能慢</td>
<td>Netty</td>
</tr>
<tr>
<td>RPS</td>
<td>&gt; 32000</td>
<td>20000 左右</td>
<td>25000 左右</td>
</tr>
<tr>
<td>Spring Cloud</td>
<td>已整合</td>
<td>已整合</td>
<td>暂无整合计划</td>
</tr>
<tr>
<td>长连接</td>
<td>支持</td>
<td>不支持</td>
<td>支持</td>
</tr>
<tr>
<td>编程体验</td>
<td>略难</td>
<td>简单易上手</td>
<td>略难</td>
</tr>
<tr>
<td>调试&amp;链路追踪</td>
<td>略难</td>
<td>无压力</td>
<td>略难</td>
</tr>
</tbody></table>
<h2 id="3-Gateway-体系架构解析"><a href="#3-Gateway-体系架构解析" class="headerlink" title="3 Gateway 体系架构解析"></a>3 Gateway 体系架构解析</h2><p>Netty 在 Gateway 中主要应用在以下几个地方：</p>
<ul>
<li>发起服务调用：由 NettyRoutingFilter 过滤器实现，底层采用基于 Netty 的 HttpClient 发起外部调用</li>
<li>Response 传输：由 NettyResponseFilter 过滤器实现，网络请求结束后要将 Response 回传给调用者</li>
<li>Socket 连接：具体由 ReactorNettyWebsocketClient 类继承，通过 Netty 的 HttpClient 发起连接请求</li>
</ul>
<p>在 Gateway 中发起 Request 和回传 Response 之类的步骤都是通过一系列过滤器完成的，有关过滤器的内容在后文稍后介绍。</p>
<p>Netty 在 Gateway 组件中的位置如下：</p>
<p><img src="https://img-blog.csdnimg.cn/img_convert/f3feeb8bd2d96787d529875fddb5be63.png" alt="5e13f0b9099a0d7930041532.png (3004×1532) (mukewang.com)"></p>
<p>Client发起请求到服务网关之后，由 NettyRoutingFilter 底层的 HttpClient（也是Netty组件）向服务发起调用，调用结束后的Response由NettyResponseFilter再回传给客户端。有了Netty的加持，网络请求效率大幅提升（Zuul 1.x还是使用Servlet，在2.x版本才移步到Netty）由此可见，Netty贯穿了从Request发起到Response结束的过程，承担了所有和网络调用相关的任务。</p>
<h3 id="3-1-Gateway-自动装配"><a href="#3-1-Gateway-自动装配" class="headerlink" title="3.1 Gateway 自动装配"></a>3.1 Gateway 自动装配</h3><p>那么Gateway 自动装配需要加载哪些资源呢？</p>
<p><img src="https://img-blog.csdnimg.cn/img_convert/f157b5764fb4d16c784ed4bc13f3e398.png"></p>
<ul>
<li>AutoConfig：核心自动装配主类，GatewayAutoConfiguration 负责初始化所有的 Route 路由规则、Predicate 断言工厂和 Filter (包括 Global Filter 和 Route Filter)，这三样是 Gateway 吃饭的家伙，用来完成路由功能。AutoConfig 也会同时加载 Netty 配置；</li>
<li>LoadBalanceClient：这部分在 AutoConfig 完成之后由 GatewayLoadBalanceClientAutoConfiguration 负责加载，用来加载 Ribbon 和一系列负载均衡配置；</li>
<li>ClassPathWarning：同样也是在 AutoConfig 完成之后触发（具体加载类为 GatewayClassPathWarningAutoConfiguration），由于 Gateway 底层依赖 Spring WebFlux 的实现，所以它会检查项目是否加载了正确配置；</li>
<li>Redis：在Gateway 中主要负责限流的功能。</li>
</ul>
<p>除了上面的核心装配工厂以外，还有其他的一些功能：</p>
<ul>
<li>GatewayMetricsAutoConfiguration 负责做一些统计工作，比如对所谓的 short task 运行时长和调用次数做统计。</li>
<li>GatewayDiscoveryClientAutoConfiguration 服务发现客户端自动装配类</li>
</ul>
<h2 id="4-路由功能详解"><a href="#4-路由功能详解" class="headerlink" title="4 路由功能详解"></a>4 路由功能详解</h2><p>Gateway 中可以定义多个 Route，一个 Route 就是一套包含完整转发规则的路由，主要由三部分组成：</p>
<p><img src="https://img-blog.csdnimg.cn/img_convert/b895129eee8c7e9884625ff8ec753f9a.png"></p>
<ul>
<li><strong>断言集合：</strong>断言是路由处理的第一个环节，它是路由的匹配规则，它决定了一个网络请求是否可以匹配到当前路由来处理。之所以它是一个集合的原因是我们可以给一个路由添加多个断言，当每个断言都匹配成功之后才算过了路由的第一步。</li>
<li><strong>过滤器集合：</strong>如果请求通过了前面的断言匹配，那就表示该请求正式被当前路由处理，接下来这个请求需要经过一系列的过滤器集合。而过滤器的功能就是八仙过海各显神通了，可以对当前请求做一系列的操作，比如权限验证，或者将其它非业务性校验的规则提取到网关过滤器这一层。在过滤器这层依然可以对请求做一些额外操作，例如可以修改 Response 里的 Status Code 达到中断效果，如把鉴权失败的请求中的 Status Code设置为 403，然后中断操作。</li>
<li><strong>URI：</strong>如果请求顺利地通过了过滤器集合，接下来的就是转发请求了。URI 是统一资源标识符，它可以是一个具体的网址，也可以是 IP + 端口的组合，或者可以是注册中心的服务名。</li>
</ul>
<h3 id="4-1-路由的工作流程"><a href="#4-1-路由的工作流程" class="headerlink" title="4.1 路由的工作流程"></a>4.1 路由的工作流程</h3><p><img src="https://img-blog.csdnimg.cn/img_convert/5caf80b8df7d33ffdd1e9c940737c89d.png"></p>
<ul>
<li><p>Predicate Handler</p>
<p>具体实现类是<code>RoutePredicateHandlerMapping</code>。首先它获取所有的路由（配置的 routes 全集），然后依次循环每个 Route，把应用请求与 Route 中配置的所有断言进行匹配，如果当前 Route 所有断言都验证通过，Predicate Handler 就选定当前路由。这个设计模式是职责链设计模式。</p>
</li>
<li><p>Filter Handler</p>
<p>在前一步选中路由后，由 FilterWebHandler 将请求交给过滤器，在具体处理过程中， 不仅当前Route中定义的过滤器会生效，在项目中添加的全局过滤器（Global Filter）也会一同参与。</p>
<p>Pre Filter 和 Post Filter 是过滤器的应用阶段，稍后介绍。</p>
</li>
<li><p>寻址</p>
<p>这一步将请求转发到 URI 指定的路径，在发送请求之前，所有 Pre 类型的过滤器都将被执行，而 Post 过滤器会在调用请求返回之后起作用。</p>
</li>
</ul>
<h2 id="5-断言功能详解"><a href="#5-断言功能详解" class="headerlink" title="5 断言功能详解"></a>5 断言功能详解</h2><h3 id="5-1-Predicate-机制"><a href="#5-1-Predicate-机制" class="headerlink" title="5.1 Predicate 机制"></a>5.1 Predicate 机制</h3><p>Predicate 是 Java 8 中引入的一个新功能，就和我们平时在项目中写单元测试时用到的 Assertion 差不多，Predicate 接受一个判断条件，返回一个 true 或 false 的布尔值结果，告知调用方判断结果。你也可以通过“与”、“或”和“非”三个操作符将多个 Predicate 串联在一起共同判断。</p>
<p>Predicate 就是一种路由规则，通过 Gateway 中丰富的内置断言的组合，我们就能让一个请求找到对应的 Route 来处理。</p>
<h3 id="5-2-断言的作用阶段"><a href="#5-2-断言的作用阶段" class="headerlink" title="5.2 断言的作用阶段"></a>5.2 断言的作用阶段</h3><p>一个请求进入网关之后，首先要先进行断言匹配，在满足所有断言之后才会进入 Filter 阶段。有关 Filter 的内容将在之后介绍，本小节不做介绍。</p>
<h3 id="5-3-常用断言介绍"><a href="#5-3-常用断言介绍" class="headerlink" title="5.3 常用断言介绍"></a>5.3 常用断言介绍</h3><h4 id="5-3-1-Path-断言"><a href="#5-3-1-Path-断言" class="headerlink" title="5.3.1 Path 断言"></a>5.3.1 Path 断言</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/gateway/**&quot;</span>)</span><br><span class="line">             .uri(<span class="string">&quot;lb://FEIGN-SERVICE-PROVIDER/&quot;</span>)</span><br><span class="line">)</span><br><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/baidu&quot;</span>)</span><br><span class="line">             .uri(<span class="string">&quot;http://baidu.com:80/&quot;</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>Path 断言的使用非常简单，就像我们在 Controller 中配置 <code>@RequestMapping</code> 的方式一样，在 Path 断言中填上一段 URL 匹配规则，当实际请求的 URL 和断言中的规则相匹配的时候，就下发到该路由中 URI 指定的地址，这个地址可以是一个具体的 HTTP 地址，也可以是注册中心中注册的服务名称。</p>
<h4 id="5-3-2-Method-断言"><a href="#5-3-2-Method-断言" class="headerlink" title="5.3.2 Method 断言"></a>5.3.2 Method 断言</h4><p>这个断言是专门验证 HTTP Method 的，在下面的例子中，我们把 Method 断言和 Path 断言通过一个 and 连接符合并起来，共同作用于路由判断，当我们访问“/gateway/sample”并且 HTTP Method 是 GET 的时候，将适配下面的路由。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/gateway/**&quot;</span>)</span><br><span class="line">             .and().method(HttpMethod.GET)</span><br><span class="line">             .uri(<span class="string">&quot;lb://FEIGN-SERVICE-PROVIDER/&quot;</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h4 id="5-3-3-RequestParam匹配"><a href="#5-3-3-RequestParam匹配" class="headerlink" title="5.3.3 RequestParam匹配"></a>5.3.3 RequestParam匹配</h4><p>请求断言也是在业务中经常使用的，它会从ServerHttpRequest中的Parameters列表中查询指定的属性，有如下两种不同的使用方式。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/gateway/**&quot;</span>)</span><br><span class="line">             .and().method(HttpMethod.GET)</span><br><span class="line">             .and().query(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;test&quot;</span>)</span><br><span class="line">             .and().query(<span class="string">&quot;age&quot;</span>)</span><br><span class="line">             .uri(<span class="string">&quot;lb://FEIGN-SERVICE-PROVIDER/&quot;</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<ul>
<li><p>属性名验证</p>
<p>如<code>query(&quot;age&quot;)</code>，此时断言只会验证QueryPrameters列表中是否包含了一个叫age的属性，并不会验证它的值。</p>
</li>
<li><p>属性值验证</p>
<p>如<code>query(&quot;name&quot;, &quot;test&quot;)</code>，它不仅会验证name属性是否存在，还会验证它的值是不是和断言相匹配，比如当前的断言会验证请求参数中的name属性值是不是test，第二个参数实际上是一个用作模式匹配的正则表达式。</p>
</li>
</ul>
<h4 id="5-3-4-Header-断言"><a href="#5-3-4-Header-断言" class="headerlink" title="5.3.4 Header 断言"></a>5.3.4 Header 断言</h4><p>这个断言会检查Header中是否包含了响应的属性，通常可以用来验证请求是否携带了访问令牌，比如如下设置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/gateway/**&quot;</span>)</span><br><span class="line">             .and().header(<span class="string">&quot;Authorization&quot;</span>)</span><br><span class="line">             .uri(<span class="string">&quot;lb://FEIGN-SERVICE-PROVIDER/&quot;</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>上面的断言指定了Header中必须包含一个<code>Authorization</code>属性，Header断言和Query断言一样，也可以通过传入两个参数的形式对属性值进行检查</p>
<h4 id="5-3-5-Cookie-断言"><a href="#5-3-5-Cookie-断言" class="headerlink" title="5.3.5 Cookie 断言"></a>5.3.5 Cookie 断言</h4><p>顾名思义，Cookie验证的是Cookie中保存的信息，Cookie断言和上面介绍的两种断言使用方式大同小异，唯一的不同是它必须连同属性值一同验证，不能单独只验证属性是否存在，示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/gateway/**&quot;</span>)</span><br><span class="line">             .and().cookie(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;test&quot;</span>)</span><br><span class="line">             .uri(<span class="string">&quot;lb://FEIGN-SERVICE-PROVIDER/&quot;</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h4 id="5-3-6-时间片匹配"><a href="#5-3-6-时间片匹配" class="headerlink" title="5.3.6 时间片匹配"></a>5.3.6 时间片匹配</h4><p>时间匹配有三种模式，分别是Before、After和Between，这些断言指定了在什么时间范围内路由才会生效</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">.route(r -&gt; r.path(<span class="string">&quot;/gateway/**&quot;</span>)</span><br><span class="line">             .and().before(ZonedDateTime.now().plusMinutes(<span class="number">1</span>))</span><br><span class="line">             .uri(<span class="string">&quot;lb://FEIGN-SERVICE-PROVIDER/&quot;</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>以Before断言为例，它接受的是一个ZonedDateTime参数，用来表示生效的时间。比如上面的例子中我们使用了<code>ZonedDateTime.now().plusMinutes(1)</code>表示当前时间的后一分钟，由于路由的规则是在项目启动时加载的，那么这里的当前时间也就是项目加载完成的时间，因此该路由的有效时间就是服务启动后的一分钟以内。</p>
<h4 id="5-3-7-自定义断言"><a href="#5-3-7-自定义断言" class="headerlink" title="5.3.7 自定义断言"></a>5.3.7 自定义断言</h4><p>Gateway也提供了一个扩展方法，用来将自定义的断言应用到路由上。</p>
<ul>
<li> 提示1：所有断言类都可以继承自<code>AbstractRoutePredicateFactory</code></li>
<li> 提示2：在路由配置时可以通过<code>predicate</code>或者传入一个自定义断言</li>
</ul>
<h2 id="6-过滤器的原理和生命周期"><a href="#6-过滤器的原理和生命周期" class="headerlink" title="6 过滤器的原理和生命周期"></a>6 过滤器的原理和生命周期</h2><h3 id="6-1-过滤器的设计模式"><a href="#6-1-过滤器的设计模式" class="headerlink" title="6.1 过滤器的设计模式"></a>6.1 过滤器的设计模式</h3><p>其实所有的开源框架的实现过滤器的模式都是大同小异，通过一种类似职责链的方式，传统的职责链模式中的事件会传递直到有一个处理对象接手，Gateway 中的过滤器经过优先级的排列，所有网关请求从最高优先级的过滤器开始，一路走到底，直到被最后一个过滤器处理。</p>
<h3 id="6-2-过滤器的实现方式"><a href="#6-2-过滤器的实现方式" class="headerlink" title="6.2 过滤器的实现方式"></a>6.2 过滤器的实现方式</h3><p>在 Gateway 中实现一个过滤器非常简单，只要实现 GatewayFilter 接口的默认方法就好了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Mono&lt;Void&gt; <span class="title">filter</span><span class="params">(ServerWebExchange exchange, GatewayFilterChain chain)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 随意发挥</span></span><br><span class="line">    <span class="keyword">return</span> chain.filter(exchange);    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里面有两个关键信息</p>
<ul>
<li><p>ServerWebExchange</p>
<p>这是 Spring 封装的 HTTP request-response 交互协议，从中我们可以获取 request 和 response 中的各种请求参数，也可以向其中添加内容</p>
</li>
<li><p>GatewayFilterChain</p>
<p>它是过滤器的调用链，在方法结束的时候我们需要将 exchange 对象传入调用链中的下一个对象。</p>
</li>
</ul>
<h3 id="6-3-过滤器的执行阶段"><a href="#6-3-过滤器的执行阶段" class="headerlink" title="6.3 过滤器的执行阶段"></a>6.3 过滤器的执行阶段</h3><p>不同于 Zuul 中对过滤器的 Pre 和 Post 的定义，Gateway 是通过 Filter 中的代码来实现类似 Post 和 Pre 的效果。</p>
<p>Pre 和 Post 是值当前过滤器的执行阶段，Pre 是在下一个过滤器之前被执行，Post 是在过滤器执行过后在执行。我们也可以在过滤器中同时定义 Pre 和 Post 的执行逻辑。</p>
<h4 id="6-3-1-Pre-类型"><a href="#6-3-1-Pre-类型" class="headerlink" title="6.3.1 Pre 类型"></a>6.3.1 Pre 类型</h4><p>我们就拿 AddResponseHeaderGatewayFilterFactory 举例，它可以向 Response 中添加 Header 信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> GatewayFilter <span class="title">apply</span><span class="params">(NameValueConfig config)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> (exchange, chain) -&gt; &#123;</span><br><span class="line">        exchange.getResponse().getHeaders().add(config.getName(), config.getValue());</span><br><span class="line">        <span class="keyword">return</span> chain.filter(exchange);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里的具体执行方法是定义在调用<code>chain.filter()</code>方法之前，也就是在转发到下级调用链路之前执行的，因此可以理解为一个 Pre 类型的过滤器。</p>
<h4 id="6-3-2-Post-类型"><a href="#6-3-2-Post-类型" class="headerlink" title="6.3.2 Post 类型"></a>6.3.2 Post 类型</h4><p>我们拿 SetStatusGatewayFilterFactory 举例，它在过滤器执行完毕之后，将制定的 HTTP status 返回给调用方。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> chain.filter(exchange).then(Mono.fromRunnable(() -&gt; &#123;</span><br><span class="line">		<span class="comment">// 这里是业务逻辑</span></span><br><span class="line">		&#125;));</span><br></pre></td></tr></table></figure>

<p>这个过滤器的主要逻辑在 then 方法中，then 是一个回调函数，在下级调用链路都完成以后在执行，因此这类过滤器可以看作是 Post Filter。</p>
<h3 id="6-4-过滤器优先级"><a href="#6-4-过滤器优先级" class="headerlink" title="6.4 过滤器优先级"></a>6.4 过滤器优先级</h3><p>在 Gateway 中，我们可以通过实现 <code>org.springframework.core.Ordered</code>接口或添加<code>@Order</code>注解，来给过滤器指定执行顺序，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E7%BD%91%E5%85%B3/" rel="tag"># 网关</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/04/15/docs/MySQL/MySQL%E4%BA%8B%E5%8A%A1%E7%9A%844%E7%A7%8D%E9%9A%94%E7%A6%BB%E7%BA%A7%E5%88%AB/" rel="prev" title="MySQL事务的4种隔离级别">
                  <i class="fa fa-chevron-left"></i> MySQL事务的4种隔离级别
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/05/07/docs/%E5%BE%AE%E6%9C%8D%E5%8A%A1/%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8%E9%93%BE%E8%B7%AF%E8%BF%BD%E8%B8%AA/" rel="next" title="服务调用链路追踪">
                  服务调用链路追踪 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
